package com.zhiyou100.weather.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhiyou100.weather.mapper.CityMapper;
import com.zhiyou100.weather.pojo.WeatherData;
import com.zhiyou100.weather.pojo.WeatherResponse;
import com.zhiyou100.weather.service.CityService;
import com.zhiyou100.weather.service.IWeatherDataService;
import com.zhiyou100.weather.utils.RedisUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service("cityService")
public class CityServiceImpl implements CityService {
    @Resource
    private CityMapper cityMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private IWeatherDataService iWeatherDataService;

    @Override
    public List findByContryZh(String cZh) {

        return cityMapper.findByContryZh(cZh);
    }

    @Override
    public List findByleaderZh(String cZh) {
        return cityMapper.findByleaderZh(cZh);
    }

    @Override
    public List findBycityZh(String cZh) {
        return cityMapper.findBycityZh(cZh);
    }

    @Override
    public WeatherResponse getAll(String id) {
        String URL = "http://wthrcdn.etouch.cn/weather_mini?citykey=";
        Set<String> keys = redisUtils.keys(URL + id);
        ObjectMapper objectMapper = new ObjectMapper();
        WeatherResponse weatherResponse = null;
        if (keys.size() > 0) {
            for (String key : keys
            ) {
                String body = (String) redisUtils.get(key);
                try {
                    weatherResponse = objectMapper.readValue(body, WeatherResponse.class);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return weatherResponse;
        } else {
            //查询拉取数据
            ResponseEntity<String> entity = restTemplate.getForEntity(URL + id, String.class);
            String body = entity.getStatusCodeValue() == 200 ? entity.getBody() : null;
            //封装到Redis中
            redisTemplate.opsForValue().set(URL + id, body);

            WeatherResponse weatherResponse1 = iWeatherDataService.getDataByCityId(id);
            return weatherResponse1;
        }
    }
}
